package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @author: atguigu
 * @create: 2023-11-13 10:13
 */
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConstantProperties props;

    /**
     * 图片（专辑封面、声音封面、用户头像）上传
     *
     * @param file 上传文件
     * @return 上传文件后在线路径，用于预览
     */
    @Override
    public String imageFileUpload(MultipartFile file) {
        try {
            //1.验证图片文件是否合法（是否为图片）
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null) {
                throw new GuiguException(400, "图片格式非法！");
            }

            //2.将文件上传到MInIO
            //2.1 构建上传后minio文件名称  形式：/年-月-日/随机文件名称.后缀
            String folderName = DateUtil.today();
            String fileName = IdUtil.simpleUUID();
            String extName = FileUtil.extName(file.getOriginalFilename());  //a.png--> png
            String objectName = "/" + folderName + "/" + fileName + "." + extName;
            //2.2 调用MInIO客户端完成文件上传
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(props.getBucketName()).object(objectName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            //3.返回上传成功后文件在线地址
            return props.getEndpointUrl() + "/" + props.getBucketName() + objectName;
        } catch (Exception e) {
            log.error("[专辑服务]图片文件上传异常：{}", e);
            throw new RuntimeException(e);
        }
    }
}
